/**
 * Created by jaliu on 2015/2/13.
 */


var Community = mongoose.model('community');
var User = mongoose.model('user');
var UserAuthentication = mongoose.model('user_authentications');
var async = require('async');
var moment = require('moment');
var UserFollowups = mongoose.model('user_followups');
var NumberGroup = mongoose.model('backoffice_user_numbergroup');

/**
 * 查询全部小区
 */
exports.getAllCommunityService = function (callback) {
    Community.find(null).exec(function (err, results) {
        if (results != null) {
            callback(null, results);
        } else {
            var msg = {
                "message": 'No such community'
            }
            callback(msg, null);
        }
    });
};

exports.searchMobile = function (mobilePhone, callback) {

    //var mobPhone;
    //if(mobilePhone == 'all'){
    //
    //}

    User.find({mobilePhone: mobilePhone + ""}).sort('-dateCreated').exec(function (err, results) {
        if (results != null) {
            var allData = [];
            results.forEach(function (result) {
                logger.info(result)
                var data = {
                    objId: result.objId,
                    community: result.community,
                    mobilePhone: result.mobilePhone,
                    communityName: result.communityName,
                    nickName: result.nickName,
                    userId: result._id
                };
                //var data = result;
                allData.push(data);
            });
            callback(null, allData);
        } else {
            var msg = {
                "message": 'No such mobile'
            }
            callback(msg, null);
        }
    });

};

exports.searchFrontendUserService = function (communityObjId, mobilePhone, nickName, isVUser, isTalent, userRole,startDate, endDate, startPage, pageSize, callback) {

    var mobilePhoneQueryCond = {mobilePhone: new RegExp(mobilePhone)};
    var nickNameQueryCond = {nickName: new RegExp(nickName)};

    var communityObjIdQueryCond = {};

    if (communityObjId != 'all') {
        communityObjIdQueryCond = {community: communityObjId};
    }

    if (mobilePhone == 'all') {
        mobilePhoneQueryCond = null;
    }
    ;
    if (nickName == 'all') {
        nickNameQueryCond = null;
    }
    ;

    var isVUserQueryCond = null;
    var isTalentQueryCond = null;
    var userRoleQueryCond = null;
    var dateQueryCond = null;

    if (isVUser == 'all') {
        isVUserQueryCond = null;
    } else if (isVUser == '是') {
        isVUserQueryCond = {authenticationStatus: true};
    } else {
        isVUserQueryCond = {authenticationStatus: false};
    }

    if (isTalent == 'all') {
        isTalentQueryCond = null;
    } else if (isTalent == '是') {
        isTalentQueryCond = {userType: 'talent'};
    } else {
        isTalentQueryCond = {userType: {'$ne': 'talent'}};
    }

    if (userRole == 'all') {
        userRoleQueryCond = null;
    } else if (userRole == '版主') {
        userRoleQueryCond = {userRole: 1};
    } else if(userRole == '物业'){
        userRoleQueryCond = {userRole: 2};
    }
    //logger.debug(userRoleQueryCond);
    dateQueryCond = {dateCreated: {'$gte': new Date(moment(startDate)), '$lte': new Date(moment(endDate).add(1, 'day')._d)}};

    //logger.debug(communityObjIdQueryCond);
    //logger.debug(mobilePhoneQueryCond);
    //
    //logger.debug(nickNameQueryCond);
    //logger.debug(isVUserQueryCond);
    //logger.debug(isTalentQueryCond);
    //
    //logger.debug(isModeratorQueryCond);
    //logger.debug(dateQueryCond);

    async.series([
        function (callbackInner) {
            User.count({$and: [communityObjIdQueryCond, mobilePhoneQueryCond, nickNameQueryCond, isVUserQueryCond, isTalentQueryCond, userRoleQueryCond, dateQueryCond]}, callbackInner);
        },
        function (callbackInner) {
            User.find({$and: [communityObjIdQueryCond, mobilePhoneQueryCond, nickNameQueryCond, isVUserQueryCond, isTalentQueryCond, userRoleQueryCond, dateQueryCond]})
                .populate('community', 'communityName')
                .populate('domainOfExpertise', 'value')
                .populate('homeTown.city', 'name')
                .populate('userPortrait', 'value')
                .sort('-dateCreated').skip(startPage).limit(pageSize).exec(function (err, result) {
                    if (result != null) {
                        result.forEach(function (temp) {
                            if (temp._doc.birthDate != null)
                                temp._doc.birthDate = moment(temp._doc.birthDate).format('YYYY-MM-DD')
                        })
                    }
                    callbackInner(null, result)
                });
        }
    ], callback);
}

exports.setCancelVUserService = function (userObjId, communityObjId, input, callback) {
    if (input.authenticationStatus == true) {
        async.series([
            function (callbackInner) {
                User.update({_id: userObjId}, {'authenticationStatus': input.authenticationStatus}, callbackInner);
            },
            function (callbackInner) {

                tempObj = new UserAuthentication();
                tempObj.user = userObjId;
                tempObj.community = communityObjId;
                //tempObj.imageURL = '';
                tempObj.status = true;
                tempObj.isValid = true;
                tempObj.refusalReason = '';
                tempObj.save(callbackInner)
            },
            function (callbackInner) {
                User.findOne({_id: userObjId}, 'invitedBy', function (err, user) {
                    callbackInner(err, user.invitedBy);
                });
            }
        ], callback);
    }
    else {
        async.series([
            function (callbackInner) {
                User.update({_id: userObjId}, {'authenticationStatus': input.authenticationStatus}, callbackInner);
            },
            function (callbackInner) {
                UserAuthentication.findOneAndRemove({user: userObjId, community: communityObjId}, callbackInner);
            }
        ], callback);
    }
}

exports.putFrontendUserToBlacklistService = function (userObjId, frozenOrNot, reason, callback) {
    User.update({_id: userObjId}, {'frozenOrNot': frozenOrNot, 'frozenReason': reason}, callback);
}

exports.setCancelFrontendUserAsTalentService = function (userObjId, talentDesc, type, callback) {
    if (type == '1') {
        User.update({_id: userObjId}, {
            'authenticationStatus': true,
            'userType': 'talent',
            'speciality': talentDesc
        }, callback);
    } else {
        User.update({_id: userObjId}, {
            'authenticationStatus': true,
            'userType': 'normalAppUser',
            'speciality': ''
        }, callback);
    }
}

exports.getUserAuthenticationInfoService = function (communityObjId, callback) {
    UserAuthentication.find({community: communityObjId}).exec(callback);
};

exports.updateService = function (id, input, callback) {
    User.update({_id: id}, input, callback);
};

exports.eachOtherFollowupService = function (user1, user2) {

    User.find({_id: {$in: [user1, user2]}}, 'community', function (err, result) {
        if (result[0].community + '' == result[1].community+'') {
            async.parallel([
                function (callback) {
                    UserFollowups.findOne({user: user1, followUser: user2}, function (err, result) {
                        if (result == null) {
                            var temp = new UserFollowups();
                            temp.category = 'user';
                            temp.user = user1;
                            temp.followUser = user2;
                            temp.save(callback);
                        } else {
                            callback()
                        }
                    })
                },
                function (callback) {
                    UserFollowups.findOne({user: user2, followUser: user1}, function (err, result) {
                        if (result == null) {
                            var temp = new UserFollowups();
                            temp.category = 'user';
                            temp.user = user2;
                            temp.followUser = user1;
                            temp.save(callback);
                        } else {
                            callback()
                        }
                    })
                }
            ])
        }
    });
};

exports.getUserInfoByFilterService = function (input, callback) {

    var opt = {};
    logger.debug(input);

    var queryUserIn = {};
    queryUserIn["$in"] = input;

    if (input.length == 1) {
        opt["huanxinUserName"] = input[0];
    } else {
        opt["huanxinUserName"] = queryUserIn;
    }
    logger.debug(opt);
    User.find(opt).populate('community', '_id communityName').exec(function (err, results) {
        if (results != null) {
            callback(null, results);
        } else {
            var msg = {
                "message": 'No such mobile'
            };
            callback(msg, null);
        }
    });


}

exports.addNumberGroupService = function (input, groupName,callback){

    var group = new NumberGroup();
    var data = {};
    var numbers = [];

    group.groupName = groupName;

    input.forEach(function(item){
        data = {};
        data.user = item._id;
        data.community = item.community._id;;
        data.nickName = item.nickName;
        data.userRemark = item.userremark;

        numbers.push(data);

    });
    logger.debug(numbers);
    group.sendNumbers = numbers;
    group.save(callback);


};

exports.getNumberGroupService = function (input, callback){

    NumberGroup.find({}).populate('sendNumbers.user', 'community nickName huanxinUserName').populate('community', '_id communityName')
        .sort('groupName')
        .exec(function (err, results) {

            if(err){
                callback(err, null);
            }else{
                callback(null, results);
            }
    });


}

exports.updateNumberGroupService = function (input,groupId,groupName,callback){

    var data = {};
    var numbers = [];

    input.forEach(function(item){
        data = {};
        data.user = item._id;
        data.community = item.community._id;
        data.nickName = item.nickName;
        data.userRemark = item.userremark;
        numbers.push(data);
    });
    logger.debug(numbers);
    NumberGroup.update({_id: groupId}, {
        'groupName': groupName,
        'sendNumbers': numbers,
        'dateLastModified': new Date()
    }, callback);

};

exports.deleteNumberGroupService = function (groupId,callback){

    NumberGroup.remove({_id: groupId}).exec(callback);

};

exports.getNumberGroupByIdService = function (groupId, callback){


    Community.find({}).exec(function (err, result) {

        var arry = {};
        async.each(result, function (item, callback) {
            arry[item.id] = item;
            callback();
        }), function (err) {

        };

        NumberGroup.find({_id: groupId}).populate('sendNumbers.user', 'community nickName huanxinUserName')
            .sort('groupName')
            .exec(function (err, results) {
                if(err){
                    callback(err, null);
                }else{
                    results[0]._doc.sendNumbers.forEach(function (item) {
                        item.user._doc['communityName'] = arry[item.user.community].communityName;
                    });
                    callback(null, results);
                }
            });

    });

}


exports.getUserByFilterService = function (input, callback) {

    User.find(input).populate('community', '_id communityName').exec(function (err, results) {
        if (results != null) {
            callback(null, results);
        } else {
            var msg = {
                "message": 'No such mobile'
            };
            callback(msg, null);
        }
    });


}

exports.getUserInfoByCommunityService = function (input, callback) {

    var opt = {};
    logger.debug(input);

    var queryUserIn = {};
    queryUserIn["$in"] = input.community;

    if (input.community.length == 1) {
        opt["community"] = input.community[0];
    } else {
        opt["community"] = queryUserIn;
    }
    if(input.userType != null){
        opt["userType"] = input.userType;
    }

    logger.debug(opt);
    User.find(opt).populate('community', '_id communityName').exec(function (err, results) {
        if (results != null) {
            callback(null, results);
        } else {
            var msg = {
                "message": 'No such mobile'
            };
            callback(msg, null);
        }
    });


}

exports.getNumberGroupByFilterService = function (input, callback){

    var opt = {
        _id : input.group
    };
    if(input.community){
        opt['sendNumbers.community'] = input.community
    }
    if(input.nickName){
        opt['sendNumbers.nickName'] = new RegExp(input.nickName);
    }

    logger.debug(opt);
    NumberGroup.find(opt).populate('sendNumbers.user', 'community nickName huanxinUserName')
        .populate('sendNumbers.community','_id communityName')
        .sort('groupName')
        .exec(function (err, results) {
            if (err) {
                callback(err, null);
            } else {
                //results[0]._doc.sendNumbers.forEach(function (item) {
                //    item.user._doc['communityName'] = arry[item.user.community].communityName;
                //});
                if(results.length>0){
                    //results[0]._doc.sendNumbers.forEach(function (item) {
                    var sendNumber = results[0]._doc.sendNumbers;
                    for (var i = sendNumber.length - 1; i >= 0; i--) {
                        if (input.community) {
                            if (sendNumber[i].user.community != input.community) {
                                sendNumber.splice(i, 1);
                                continue;
                            }
                        };
                        if (input.nickName) {
                            if (sendNumber[i].user.nickName.indexOf(input.nickName) == -1) {
                                sendNumber.splice(i, 1);
                                continue;
                            }
                            ;
                        };
                    };
                }
                logger.debug(results);
                callback(null, results);
            }
        });


}